import React from 'react'
import { fetchPost } from './common/request'
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  Lable,
  Message,
  Modal,
  Popconfirm,
  Row,
  Select,
  Table,
  TimePicker,
  Tree
} from 'antd'
import { treeDeal } from './common/common.js'
import { errorNotify, successNotify } from './common/common'
import moment from 'moment'

const TreeNode = Tree.TreeNode
const FormItem = Form.Item
const InputGroup = Input.Group

class MessageRule extends React.Component {
  constructor (props) {
    super(props)
  }

  state = {
    ruleDatas: [],
    newModalVis: false,
    record: {},
    appList: [],
    servicerList: [],
    selectedKey: null,
    showModal: false,
    modalIsNew: false,
  }

  componentDidMount = () => {
    this.getRules()
    this.getAppList()
  }

  //获取app列表
  getAppList () {
    fetchPost('/appInfo/getAppInfo',).then(json => {
      if (json.data != null) {
        var data = json.data
        treeDeal(data)
        this.setState({
          appList: data
        })
      }
    })
  }

  //获取规则列表
  getRules (appId) {
    var param = null
    if (appId) {
      param = {}
      param.appId = appId
    }
    console.log(param)
    fetchPost('/rule/getRuleInfo', param).then(json => {
      console.log(json.data)
      if (json.data != null) {
        this.setState({
          ruleDatas: json.data
        })
      }
    })
  }

  //修改规则状态
  changeRule (record) {
    fetchPost('/rule/updateRuleInfo', record).then(json => {
      //
      if (json.code != 200) {
        errorNotify('Fail to edit', json.msg)
      } else {
        successNotify('The rule was modified successfully')
        if (this.state.selectedKey)
          this.loadRuleInfo(this.state.selectedKey)
        else {
          this.loadRuleInfo()
        }
      }
    })
  }

  //修改规则状态
  addRule (record) {
    console.log(record)
    fetchPost('/rule/addRuleInfo', record).then(json => {
      if (json.code != 200) {
        errorNotify('New rule failed', json.msg)
      } else {
        successNotify('Added successfully')
        if (this.state.selectedKey)
          this.loadRuleInfo(this.state.selectedKey)
        else {
          this.loadRuleInfo()
        }
      }
    })
  }

  changeStatus = (record) => {
    record.status = (record.status)? 0 : 1
    this.changeRule(record)
  }

  // 加载树形控件（app列表）
  onLoadTreeData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.children) {
        resolve()
        return
      }
    })
  }
  renderTreeNodes = (data) => {
    return data.map((item) => {
      return <TreeNode title={item.appName} isLeaf={item.isLeaf} key={item.appId} dataRef={item}/>
    })
  }
  // 当点击app时 显示对应app信息
  loadRuleInfo = (selectedKeys) => {
    if (selectedKeys) {
      this.state.selectedKey = selectedKeys
      this.getRules(selectedKeys[0])
    } else {
      this.getRules(this.state.selectedKey)
    }
  }

  // 新增和修改对话框的维护
  showNewModal = () => {
    this.state.record = {}
    this.props.form.resetFields()
    // this.getAppList()
    // this.state.record.appId = this.state.selectedKey?this.state.selectedKey[0]: this.state.record.appId;

    this.setState({
      showModal: true,
      modalIsNew: true
    })

  }
  // 新增和修改对话框的维护
  showUpdateModal = (record) => {
    this.state.record = record
    this.props.form.resetFields()
    this.setState({
      // record : {},
      showModal: true,
      modalIsNew: false,
    })
  }
  handleVisOk = (e) => {

    this.props.form.validateFields((err, values) => {
      if (!err) {
        let param = {}
        param.appId = values.appId
        param.sendRuleName = values.sendRuleName
        param.status = values.status
        param.ruleContentList = [{}]
        param.ruleContentList[0].fact = 'sendTime'
        param.ruleContentList[0].ruleCondiction = values.condition
        param.ruleContentList[0].startSendTime = moment(values.startSendTime).format('HH:mm:ss')
        // param.ruleContentList[0].endSendDate = values.endSendDate
        param.ruleContentList[0].ruleName = values.subRuleName
        // 判断是新增还是修改
        if (this.state.modalIsNew) {
          this.addRule(param)
        } else {
          param.ruleId = this.state.record.ruleId
          this.changeRule(param)
        }
        this.setState({
          showModal: false,
        })
      }
    })

  }
  handleVisCancel = (e) => {
    this.setState({
      showModal: false,
    })
  }

  /*// 新增业务所填字段
  recordAppNameChange= (value, option)=> {
    this.state.record.bizName = null;
    this.props.form.resetFields();

    this.state.record.appId = value;
    this.state.appList.map(app => {
      var a = this.state.record
      if (app.appId == value){
        a.businessTypeId = app.businessTypeId
      }
      this.setState({
        record: a
      })
    })
  }*/

  // 删除选中
  onDeleteLists = () => {
  }

  render () {
    const dateFormat = 'YYYY-MM-DD'
    const ruleItemColumns = [{
      title: 'Sub-rule name',
      dataIndex: 'ruleName',
      key: 'ruleName',
    }, {
      title: 'Rule category',
      dataIndex: 'fact',
      key: 'fact',
    }, {
      title: 'Rule limit',
      dataIndex: 'ruleCondiction',
      key: 'ruleCondiction',
    }, {
      title: 'Send start time',
      dataIndex: 'startSendTime',
      key: 'startSendTime',
    }, {
      title: 'Send end time',
      dataIndex: 'endSendTime',
      key: 'endSendTime',
    }]

    const columns = [{
      title: 'App name',
      dataIndex: 'appName',
      key: 'appName',
    }, {
      title: 'Rule group name',
      dataIndex: 'sendRuleName',
      key: 'sendRuleName',
    }, {
      title: 'Description',
      dataIndex: 'remark',
      key: 'remark',
    }, {
      title: 'Rule status',
      dataIndex: 'status',
      key: 'status',
      render: (text, record) => {
        return (text === 1 ? 'Normal' : 'Invalid')
      }
    }
      , {
        title: 'Operate',
        dataIndex: 'action',
        key: 'action',
        render: (text, record) => {
          const {editable} = record
          return (
            <div>


              <Button style={{'margin-bottom': '10'}} onClick={this.showUpdateModal.bind(this,record)}>Modify</Button>

              <Button onClick={this.changeStatus.bind(this, record)}>
                {record.status?<span>Invalid</span>:<span>Activation</span>}
              </Button>
              {/*<Popconfirm title="确定删除该条数据?" onConfirm={() => this.onDelete(record.key)}>*/}
                {/*<Button>*/}
                  {/*删除*/}
                {/*</Button>*/}
              {/*</Popconfirm>*/}
            </div>
          )
        }
      }
    ]

    // 表单排版
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 19},
      },
    }

    // 子规则表单排版1
    const subRuleFormItemLayout1 = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 24},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 24},
      },
    }

    // app单选框
    const appOptions = this.state.appList.map(d => <Option key={d.appId}>{d.appName}</Option>)
    // if (this.state.appList){
      // console.log(typeof this.state.appList[0].appId)}
    // 服务商单选框
    const servicerOptions = this.state.servicerList.map(d => <Option key={d.servicerId}>{d.servicerName}</Option>)
    const {getFieldDecorator} = this.props.form

    return (
      <Card>
        <Row>
          <Col span={3}>
            <Tree ref="tree" loadData={this.onLoadTreeData} onSelect={this.loadTemplateInfo}>
              {this.renderTreeNodes(this.state.appList)}
            </Tree>
          </Col>
          <Col span={21}>
            <div>
              <Button style={{'margin-bottom': '10'}} onClick={this.showNewModal}>New configuration</Button>
              <Popconfirm title="Make sure to delete these data?" onConfirm={() => this.onDeleteLists()}>
                <Button style={{display: 'none'}}>
                  Delete selected
                </Button>
              </Popconfirm>
            </div>
            <Table ref="table" dataSource={this.state.ruleDatas} onChange={this.handleChange} columns={columns}
                   rowKey="ruleId"
                   expandedRowRender={record =>
                     <Table dataSource={record.ruleContentList} columns={ruleItemColumns} pagination={false}>
                     </Table>
                     // <p style={{ margin: 0 }}>12312312s{record.ruleName}</p>
                   }>
            </Table>
          </Col>
        </Row>

        <Modal
          title={this.state.modalIsNew ? 'Add' : 'Modify'}
          visible={this.state.showModal}
          onOk={this.handleVisOk}
          onCancel={this.handleVisCancel}
        >
          <Form>
            <Card title="Rule group">

              <FormItem {...formItemLayout} label="App name">
                {getFieldDecorator('appId', {
                  initialValue: this.state.record.appId ? this.state.record.appId+''  : '',
                  rules: [
                    {required: true, message: 'Please enter the app name!'},
                  ],
                })(
                  <Select disabled={!this.state.modalIsNew}>
                    {appOptions}
                  </Select>
                )}
              </FormItem>

              <FormItem {...formItemLayout} label="Rule group name">
                {getFieldDecorator('sendRuleName', {
                  initialValue: this.state.record ? this.state.record.sendRuleName || '' : '',

                  rules: [
                    {required: true, message: 'Please enter a rule group name!'},
                  ],
                })(
                  <Input placeholder="Please enter a rule group name"/>
                )}
              </FormItem>

              <FormItem {...formItemLayout} label="Status">
                {getFieldDecorator('status', {
                  initialValue: this.state.record.status || 1,
                  rules: [
                    {required: true, message: 'Please enter the rule group status!'},
                  ],
                })(
                  <Select placeholder="Please">
                    <Option value={1}>Normal</Option>
                    <Option value={0}>Invalid</Option>
                  </Select>
                )}
              </FormItem>

              <Card
                type="inner"
                title="Sub-rule"
              >


                <FormItem {...formItemLayout} label="Sub-rule name">
                  {getFieldDecorator('subRuleName', {
                    initialValue: this.state.record.ruleContentList ? this.state.record.ruleContentList[0].ruleName || '' : '',
                    rules: [
                      {required: true, message: 'Please enter a sub-rule name!'},
                    ],
                  })(
                    <Input placeholder="Please enter a sub-rule name"/>
                  )}
                </FormItem>

                <InputGroup compact style={{width: '100%'}}>
                  <Row gutter={0} style={{width:'100%'}}>
                    <Col span={5}>
                      <FormItem {...subRuleFormItemLayout1} style={{'text-align': 'right'}} label="Sending time" required/>
                    </Col>
                    <Col span={6}>
                      <FormItem {...subRuleFormItemLayout1}>

                        {getFieldDecorator('condition', {
                          initialValue: "=",
                          rules: [
                            {required: true},
                          ],
                        })(
                          <Select style={{width: '100%'}} >
                            <Option value="=">=</Option>
                          </Select>

                        )}
                      </FormItem>
                      <div style={{position:'absolute',display:this.props.form.getFieldValue('startSendTime')?'inherit':'none',top:'36px',color:'rgba(0, 0, 0, 0.43)','white-space':'nowrap'}}>Please fill in the sending time (the date can be empty, the time cannot be empty)</div>
                    </Col>
                    {/*<Col span={6}>
                      <FormItem {...subRuleFormItemLayout1}>
                        {getFieldDecorator('startSendDate')(
                          <DatePicker style={{width: '100%'}}/>
                        )}
                      </FormItem>
                    </Col>*/}
                    <Col span={13}>
                      <FormItem extra="">
                        {getFieldDecorator('startSendTime', {
                          initialValue: this.state.modalIsNew ?
                            (moment(this.state.record.ruleContentList ? this.state.record.ruleContentList[0].startSendTime:'00:00:00', 'HH:mm:ss')) :
                            this.state.record.ruleContentList? (this.state.record.ruleContentList[0].startSendTime ? moment(this.state.record.ruleContentList[0].startSendTime,'HH:mm:ss') : null):null,
                          // initialValue: this.state.record.ruleContentList ? this.state.record.ruleContentList[0].startSendTime : moment('00:00:00', 'HH:mm:ss'),
                          rules: [
                            {required: true, message: 'Please select the sending time'},
                          ],
                        })(
                          <TimePicker style={{width: '100%'}} size="large"/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </InputGroup>

               {/* <InputGroup compact style={{width: '100%'}}>
                  <Row gutter={0} style={{width:'100%'}}>
                    <Col span={5}>
                      <FormItem {...subRuleFormItemLayout1} style={{'text-align': 'right'}} label="结束时间" required/>
                    </Col>
                    <Col span={6}>
                      <FormItem {...subRuleFormItemLayout1}>

                        {getFieldDecorator('condition', {
                          initialValue: "=",
                          rules: [
                            {required: true},
                          ],
                        })(
                          <Select style={{width: '100%'}} >
                            <Option value="=">=</Option>
                          </Select>

                        )}
                      </FormItem>
                      ,top:this.props.form.getFieldValue('endSendTime')?'36px':'48px'
                      <div style={{position:'absolute',display:this.props.form.getFieldValue('endSendTime')?'inherit':'none',top:'36px',color:'rgba(0, 0, 0, 0.43)','white-space':'nowrap'}}>请填写发送时间(日期可以为空，时间不能为空)</div>
                    </Col>
                    <Col span={6}>
                      <FormItem {...subRuleFormItemLayout1}>

                        {getFieldDecorator('endSendDate')(
                          <DatePicker style={{width: '100%'}}/>
                        )}
                      </FormItem>
                    </Col>
                    <Col span={13}>
                      <FormItem extra="">
                        {getFieldDecorator('endSendTime', {
                          initialValue: moment( this.state.record.ruleContentList ? this.state.record.ruleContentList[0].endSendTime: null, 'HH:mm:ss'),
                          rules: [
                            {required: true, message: '请选择发送结束时间'},
                          ],
                        })(
                          <TimePicker style={{width: '100%'}} size="large"/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </InputGroup>*/}
              </Card>
            </Card>
          </Form>

        </Modal>

      </Card>
    )
  }
}

MessageRule = Form.create()(MessageRule)
export default MessageRule


